import {HTTP} from "../../../utils/http.js"
import Dialog from '../../../miniprogram_npm/vant-weapp/dialog/dialog';
import { MessageModel } from "../../../models/message.js";
var _MessageModel = new MessageModel();
const app =getApp();
var http = new HTTP();
var that;

Page({
  data: {
    images: [],
    imageWidth:120
  },
  onLoad: function (options) {
   that = this;
    that.setData({
      imageWidth: Math.floor((app.globalData.windowWidth - 40-18) / 3)
    })
  },
  getContent: function (e) {
    that.setData({
      content: e.detail.value
    });
  },
  chooseImage: function () {
    // 选择图片
    wx.chooseImage({
      count:9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        let len = tempFilePaths.length;
       
        let imagesLen = that.data.images.length
        if (imagesLen + len<=9){
          that.setData({
            images: that.data.images.concat(tempFilePaths)
          });
        }else{
          var subtag = (9-that.data.images.length);
          
          that.setData({
            images: that.data.images.concat(tempFilePaths.slice(0, subtag))
          });
        }
        
      }
    })
  },
  previewImage: function () {
    // 预览图集
    wx.previewImage({
      urls: that.data.images
    });
  },
  formSubmit: function (e) {
    if (e.detail.value.content == "") {
      Dialog.alert({
        title: '提示',
        message: "请动态内容。"
      });
      return;
    }

    let data = {
      "message": e.detail.value.content
    }

    http.uploadImages(this.data.images, function (images) {
      data.messageImage = images.join(",");
      _MessageModel.publish(data,function(){
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000,
          success:function(){
            var pages = getCurrentPages();
            if (pages.length > 1) {
              var prePage = pages[pages.length - 2];
              prePage.changeData("publish");
              wx.navigateBack();
            }
          }
        })
      });
    });

  
  },
  delete: function (e) {
    var index = e.currentTarget.dataset.index;
    var images = that.data.images;
    images.splice(index, 1);
    that.setData({
      images: images
    });
  }
})